package com.rem.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rem.chat.common.errcode.ServiceErrorCodeConstants;
import com.rem.chat.common.exception.ServiceException;
import com.rem.chat.common.utils.BeanTransUtil;
import com.rem.chat.mapper.UserBeautyIdMapper;
import com.rem.chat.mapper.UserInfoMapper;
import com.rem.chat.pojo.dataobject.UserBeautyIdDO;
import com.rem.chat.pojo.dataobject.UserInfoDO;
import com.rem.chat.pojo.request.BeautyIdAddRequest;
import com.rem.chat.pojo.request.BeautyIdModifyRequest;
import com.rem.chat.pojo.request.PageRequest;
import com.rem.chat.pojo.response.LoadAllBeautyIdResponse;
import com.rem.chat.service.BeautyService;
import com.rem.chat.service.enums.BeautyAccountStatusEnum;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: Themberfue
 * @date: 2025/6/9 19:41
 * @description:
 */
@Service
public class BeautyServiceImpl implements BeautyService {

    @Resource
    UserBeautyIdMapper userBeautyIdMapper;

    @Resource
    UserInfoMapper userInfoMapper;

    @Override
    public LoadAllBeautyIdResponse loadBeautyIdList(PageRequest param) {
        // Step 1. 校验参数
        if (null == param) {
            param = new PageRequest();
        }

        // Step 2. 查询靓号的数量
        Long total = userBeautyIdMapper.selectCount(new QueryWrapper<>());

        // Step 3. 进行分页查询
        Page<UserBeautyIdDO> page = new Page<>(param.getCurrentPage(), param.getPageSize());
        QueryWrapper<UserBeautyIdDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .orderByDesc(UserBeautyIdDO::getCreateTime);
        List<LoadAllBeautyIdResponse.BeautyIdInfo> beautyIdInfoList = userBeautyIdMapper.selectList(page, queryWrapper)
                .stream()
                .map(BeanTransUtil::transToBeautyIdInfo)
                .toList();

        return new LoadAllBeautyIdResponse(total, beautyIdInfoList);
    }

    @Override
    public Boolean addBeautyId(BeautyIdAddRequest request) {
        // Step 1: 校验靓号是否已被使用
        validateBeautyIdNotUsed(request.getUserId());

        // Step 2: 校验邮箱是否已绑定靓号
        validateEmailNotBoundToBeautyId(request.getEmail());

        // Step 3: 校验邮箱是否已被普通用户注册
        validateEmailNotRegistered(request.getEmail());

        // Step 4: 保存靓号预注册信息
        saveBeautyIdRegistration(request);
        
        // Step 5. 插入数据到数据库
        return saveBeautyIdRegistration(request);
    }

    @Override
    public Boolean modifyBeautyId(BeautyIdModifyRequest request) {
        // Step 1: 校验靓号是否存在
        UserBeautyIdDO beautyIdDO = validateBeautyIdExists(request.getId());

        // Step 2: 校验靓号是否未被使用
        validateBeautyIdNotUsed(beautyIdDO);

        // Step 3: 更新靓号信息并绑定用户
        return updateAndBindBeautyId(beautyIdDO, request);
    }

    @Override
    public Boolean delBeautyId(Integer id) {
        // Step 1: 校验靓号是否存在
        UserBeautyIdDO beautyIdDO = validateBeautyIdExists(id);

        // Step 2: 校验靓号是否未被使用
        validateBeautyIdNotUsed(beautyIdDO);

        // Step 3. 删除数据到数据库
        return userBeautyIdMapper.deleteById(id) > 0;
    }

    private Boolean saveBeautyIdRegistration(BeautyIdAddRequest request) {
        UserBeautyIdDO beautyIdDO = UserBeautyIdDO.builder()
                .userId(request.getUserId())
                .email(request.getEmail())
                .status(BeautyAccountStatusEnum.NO_USE.getStatus())
                .build();
        return userBeautyIdMapper.insert(beautyIdDO) > 0;
    }

    private void validateEmailNotRegistered(String email) {
        QueryWrapper<UserInfoDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UserInfoDO::getEmail, email);
        UserInfoDO userInfoDO = userInfoMapper.selectOne(queryWrapper);
        if (null != userInfoDO) {
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_HAD_USED);
        }
    }

    private void validateEmailNotBoundToBeautyId(String email) {
        QueryWrapper<UserBeautyIdDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UserBeautyIdDO::getEmail, email);
        UserBeautyIdDO userBeautyIdDO = userBeautyIdMapper.selectOne(queryWrapper);
        if (null != userBeautyIdDO) {
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_IS_BIND_ID);
        }
    }

    private void validateBeautyIdNotUsed(String userId) {
        QueryWrapper<UserBeautyIdDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UserBeautyIdDO::getUserId, userId);
        UserBeautyIdDO userBeautyIdDO = userBeautyIdMapper.selectOne(queryWrapper);
        if (null != userBeautyIdDO) {
            throw new ServiceException(ServiceErrorCodeConstants.BEAUTY_ID_IS_EXISTS);
        }
    }

    private Boolean updateAndBindBeautyId(UserBeautyIdDO beautyIdDO, BeautyIdModifyRequest request) {
        // 更新靓号信息
        beautyIdDO.setUserId(request.getUserId());
        beautyIdDO.setEmail(request.getEmail());
        beautyIdDO.setStatus(BeautyAccountStatusEnum.USED.getStatus()); // 标记为已使用

        // 执行更新
        return userBeautyIdMapper.updateById(beautyIdDO) > 0;
    }

    private void validateBeautyIdNotUsed(UserBeautyIdDO beautyIdDO) {
        if (BeautyAccountStatusEnum.USED.getStatus().equals(beautyIdDO.getStatus())) {
            throw new ServiceException(ServiceErrorCodeConstants.BEAUTY_ID_USED);
        }
    }

    private UserBeautyIdDO validateBeautyIdExists(Integer beautyId) {
        UserBeautyIdDO beautyIdDO = userBeautyIdMapper.selectById(beautyId);
        if (beautyIdDO == null) {
            throw new ServiceException(ServiceErrorCodeConstants.BEAUTY_ID_IS_NOT_EXISTS);
        }
        return beautyIdDO;
    }
}
